/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Yahtzee;

/**
 *
 * @author agreseth
 */
import java.io.*;
import java.net.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import javax.swing.*;
public class Client {

    Socket echoSocket;
    PrintWriter out;
    BufferedReader in;
    BufferedReader stdIn;
    ServerGUI gui;
    String player2IP;
    String myIP;
    GUI yah;
    Executor executor;
    boolean gameStarted = false;;

public Client()
{
        //removed "Socket", "PrintWriter", etc...
        echoSocket = null;
        out = null;
        in = null;
}
public void start(String ip, int port, ServerGUI gu)
{
    gui = gu;
        try {
            
            echoSocket = new Socket(ip, port);
            myIP = echoSocket.getLocalAddress().toString();
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                                        echoSocket.getInputStream()));
            
            String temp = "";
//            while((temp = in.readLine()) != null)          
//            {
//                gui.messagesTextArea.append(temp);
//            }
            //System.out.println(in.readLine());
            
            //send your clients ip address
            out.println(echoSocket.getLocalAddress());


            while(true)
            {
                System.out.println("I'm Looping");
            String whynot = recv();
            System.out.println(whynot + "really");
            
            // used to detect if your client was selected to start a game
            if (whynot.startsWith("Game On"))
            {
                yah = new GUI();
                gameStarted = true;
                yah.setVisible(true);
                yah.player2Label.setText(whynot.substring(7));
                processGame();
            }

            // grab the ips from the server
            int ipTotal;
            int find = whynot.indexOf("/");
            ipTotal = Integer.parseInt(whynot.substring(0, find));
            String blah[] = whynot.split("/");
            // clear out the items from the combobox
            gui.selectPlayer.removeAllItems();
            // loop through each ip in the list and add them to the combobox
            for (int i = 1;i < ipTotal + 1;i++)
            {
                //porque[i] = whynot.substring(2, whynot.indexOf("/"));
                System.out.println(blah[i]);
                gui.selectPlayer.addItem(gui.makeObj(blah[i]));
            }
            System.out.println("Out of for loop");
            gui.messagesTextArea.setText(whynot);
            //gui.messagesTextArea.setText(in.readLine());
            //out.println("Final Score 2999 <end>");
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection to: taranis.");
            System.exit(1);
        }

//        // get info from server, output to screen
//        try{
//        //String fromServer = in.readLine();
//        //System.out.println(fromServer);
//        }
//        catch(Exception e)
//        {
//
//        }
//
//
//	stdIn = new BufferedReader(new InputStreamReader(System.in));
//	String userInput;
//
////	while ((userInput = stdIn.readLine()) != null) {
////	    out.println(userInput);
////	    System.out.println("echo: " + in.readLine());
//
////	}
//        try
//        {
//            //String fromServer = in.readLine();
//            //System.out.println("This is legit");
//            //System.out.println(fromServer);
//        }
//        catch (Exception e)
//        {
//            System.out.println("Problem reading input!");
//        }

}



        public void close()
        {
            try
            {

                out.close();
                in.close();
                stdIn.close();
                echoSocket.close();
            }
            catch (Exception e)
            {
                System.out.println("Client closing failed!");
            }
        }

        // start up the game for this client
        public String startGame(String otherIP, GUI ya)
        {
            yah = ya;
            System.out.println("I got called");
            player2IP = otherIP;
            //tell server that you are starting a game, the server will tell the other client
            String test = "Start " + myIP + "^" + player2IP + "<end>";
            yah.player2Label.setText(otherIP);
            System.out.println(test);
            out.println(test);
            return null;
        }
        
        public void sendScore(int[] s)
        {
            out.println("Ones"+ s);
            out.print(s);
        }
        
        public void processGame()
        {
            System.out.println("Starting to process game");

            // executor which allows multiple background threads, this will allow for input and output
            // to occur at the same time
            executor = Executors.newCachedThreadPool();
            SwingWorker worker = new SwingWorker<Void, Void>()
            {
            @Override
             public Void doInBackground()
            {
                System.out.println("In Background");
                executeGame();
                return null;
            }

            };
            executor.execute(worker);

            boolean ones = false;
            boolean twos = false;
            boolean threes = false;
            boolean fours = false;
            boolean fives = false;
            boolean sixes = false;
            boolean threekind = false;
            boolean fourkind = false;
            boolean fullhouse = false;
            boolean smallstraight = false;
            boolean largestraight = false;
            boolean yahtzee = false;
            boolean chance = false;

            System.out.println(yah.yThreeKindField.getText().isEmpty());
            System.out.println(yah.yOneField.getText().isEmpty());
            // will loop through looking for score in gui
            // when score occurs send the score to the server
            while(!ones || !twos || !threes || !fours || !fives || !sixes || !threekind || !fourkind || !fullhouse || !smallstraight || !largestraight || !yahtzee || !chance)
            {
                if (!yah.yOneField.getText().isEmpty() && !ones)
                {
                    out.println("Ones"+yah.yOneField.getText());                    
                    System.out.println("Ones was scored");
                    ones = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if (!yah.yTwoField.getText().isEmpty() && !twos)
                {
                    out.println("Twos"+yah.yTwoField.getText());
                    System.out.println("Twos was scored");
                    twos = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if (!yah.yThreeField.getText().isEmpty() && !threes)
                {
                    out.println("Threes"+yah.yThreeField.getText());
                    System.out.println("Threes was scored");
                    threes = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if (!yah.yFourField.getText().isEmpty() && !fours)
                {
                    out.println("Fours"+yah.yFourField.getText());
                    System.out.println("Fours was scored");
                    fours = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if (!yah.yFiveField.getText().isEmpty() && !fives)
                {
                    out.println("Fives"+yah.yFiveField.getText());
                    System.out.println("Fives was scored");
                    fives = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if (!yah.ySixField.getText().isEmpty() && !sixes)
                {
                    out.println("Sixes"+yah.ySixField.getText());
                    System.out.println("Sixes was scored");
                    sixes = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if(!yah.yThreeKindField.getText().isEmpty() && !threekind)
                {
                    System.out.println("Three"+yah.yThreeKindField.getText());
                    out.println("ThreeKind"+yah.yThreeKindField.getText());
                    System.out.println("Three Kind was scored");
                    threekind = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if(!yah.yFourKindField.getText().isEmpty() && !fourkind)
                {
                    out.println("FourKind"+yah.yFourKindField.getText());
                    System.out.println("Four Kind was scored");
                    fourkind = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if(!yah.yFullHouseField.getText().isEmpty() && !fullhouse)
                {
                    out.println("FullHouse"+yah.yFullHouseField.getText());
                    System.out.println("Full House was scored");
                    fullhouse = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if(!yah.ySmStField.getText().isEmpty() && !smallstraight)
                {
                    out.println("SmallStraight"+yah.ySmStField.getText());
                    System.out.println("Small Straight was scored");
                    smallstraight = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if(!yah.yLgStField.getText().isEmpty() && !largestraight)
                {
                    out.println("LargeStraight"+yah.yLgStField.getText());
                    System.out.println("Large Straight was scored");
                    largestraight = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if(!yah.yYahtzeeField.getText().isEmpty() && !yahtzee)
                {
                    out.println("Yahtzee"+yah.yYahtzeeField.getText());
                    System.out.println("Yahtzee was scored");
                    yahtzee = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }
                else if(!yah.yChanceField.getText().isEmpty() && !chance)
                {
                    out.println("Chance"+yah.yChanceField.getText());
                    System.out.println("Chance was scored");
                    chance = true;
                    out.println("UpperScore"+yah.yUpperScore.getText());
                    out.println("Bonus"+yah.yBonusField.getText());
                    out.println("YahtzeeBonus"+yah.yYahtzeeBonus.getText());
                    out.println("TotalScore"+yah.yTotalScore.getText());
                    out.println("LowerScore"+yah.yLowerScoreField.getText());
                }

            }
            System.out.println("Out of Loop must be done scoring");
            out.println("FinalScore"+yah.yTotalScore);
        }


        // this handles receiving the other players scores from the server
        public void executeGame()
        {
            while(true)
            {
                    String input = recv();
                    if (input.startsWith("Ones"))
                    {
                        String ones = input.substring(4);
                        yah.tOneField.setText(ones);                       
                    }                
            }
        }

        // recv from the server
        public String recv()
        {
        String input = "";
        try
        {
            input = in.readLine();

            // determine if the info from server is a score or not
            if(input.contains("Ones"))
            {
                String ones = input.substring(4);
                yah.tOneField.setText(ones);
            }
             else if (input.startsWith("Twos"))
             {
                 String twos = input.substring(4);
                 yah.tTwoField.setText(twos);
             }
             else if (input.startsWith("Threes"))
             {
                 String threes = input.substring(6);
                 yah.tThreeField.setText(threes);
             }
             else if (input.startsWith("Fours"))
             {
                 String fours = input.substring(5);
                 yah.tFourField.setText(fours);
             }
             else if (input.startsWith("Fives"))
             {
                 String fives = input.substring(5);
                 yah.tFiveField.setText(fives);
             }
            else if (input.startsWith("Sixes"))
             {
                 String sixes = input.substring(5);
                 yah.tSixField.setText(sixes);
             }
            else if(input.startsWith("ThreeKind"))
            {
                yah.tThreeKindField.setText(input.substring(9));
            }
            else if(input.startsWith("FourKind"))
            {
                yah.tFourKindField.setText(input.substring(8));
            }
            else if(input.startsWith("FullHouse"))
            {
                yah.tFullHouseField.setText(input.substring(9));
            }
            else if(input.startsWith("SmallStraight"))
            {
                yah.tSmStField.setText(input.substring(13));
            }
            else if(input.startsWith("LargeStraight"))
            {
                yah.tLgStField.setText(input.substring(13));
            }
            else if(input.startsWith("Yahtzee") & (input.length() < 10))
            {
                yah.tYahtzeeField.setText(input.substring(7));
            }
            else if(input.startsWith("Chance"))
            {
                yah.tChanceField.setText(input.substring(6));
            }
            else if (input.startsWith("UpperScore"))
             {
                 String upper = input.substring(10);
                 yah.tUpperScore.setText(upper);
             }
            else if(input.contains("Bonus") & (input.length() < 10))
            {
                String bonus = input.substring(5);
                 yah.tBonusField.setText(bonus);
            }
            else if(input.contains("YahtzeeBonus"))
            {
                String yb = input.substring(12);
                 yah.tYahtzeeBonus.setText(yb);
            }
            else if(input.contains("TotalScore"))
            {
                String total = input.substring(10);
                 yah.tTotalScore.setText(total);
            }
            else if(input.contains("LowerScore"))
            {
                String lower = input.substring(10);
                yah.tLowerScoreField.setText(lower);
            }

            else
            {
                //System.out.println("Input "+ input);
            }
        }
        // Recv broke, meaning the server properly went way so close the client
        catch(Exception e)
        {
            System.out.println("Receive Fail");
            System.exit(0);
        }
        if (gameStarted)
        {
            executeGame();
        }
        return input;
    }
}



